#ifndef LAYERVISIBILITYDELEGATE_H
#define LAYERVISIBILITYDELEGATE_H

#endif // LAYERVISIBILITYDELEGATE_H

#include <QStyledItemDelegate>
#include <QPainter>
#include <QCheckBox>
#include <QModelIndex>
#include <QStyleOptionButton>
#include <QApplication>
#include <qgslayertreeview.h>
#include <qgslayertreemodel.h>
#include <QStandardItemModel>
#include <qgslayertreenode.h>

class LayerVisibilityDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    explicit LayerVisibilityDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}

    // 重新绘制项（绘制复选框）
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        QStyledItemDelegate::paint(painter, option, index);

        // 如果是第一列（图层名称列），绘制复选框
        if (index.column() == 0) {
            // 获取图层的可见性
            bool isChecked = index.model()->data(index, Qt::CheckStateRole).toBool();

            QStyleOptionButton checkboxStyle;
            checkboxStyle.rect = option.rect.adjusted(4, 0, 0, 0);  // 设置复选框位置
            checkboxStyle.state = isChecked ? QStyle::State_On : QStyle::State_Off;
            QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxStyle, painter);
        }
    }

    /*
    // 处理复选框的点击事件
    bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
                     const QModelIndex &index) override
    {
        if (index.column() == 0) {
            // 只有在点击第一列时，才处理复选框的点击事件
            if (event->type() == QEvent::MouseButtonRelease) {
                qDebug()<< "editorEvent-MouseButtonRelease:" << index.column();
                bool isChecked = index.model()->data(index, Qt::CheckStateRole).toBool();
                qDebug() << "Current check state: " << isChecked;
                bool newCheckedState = isChecked ? Qt::Unchecked : Qt::Checked;
                bool ret=model->setData(index, newCheckedState, Qt::CheckStateRole);
                //model->setData(index, isChecked ? Qt::Unchecked : Qt::Checked, Qt::CheckStateRole);
                qDebug() << "New check state: " << newCheckedState<<"setData ret="<<ret;
                //emit model->dataChanged(index, index);  // 显式发射 dataChanged 信号
                //layerTreeView->viewport()->update();  // 强制刷新视图
                return true;
            }
        }
        return QStyledItemDelegate::editorEvent(event, model, option, index);
    }
*/
    bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
                     const QModelIndex &index) override
    {
        if (index.column() == 0) {  // 只处理第一列的复选框点击
            if (event->type() == QEvent::MouseButtonRelease) {
                qDebug() << "editorEvent-MouseButtonRelease:" << index.column();

                // 获取当前复选框状态
                bool isChecked = index.model()->data(index, Qt::CheckStateRole).toBool();
                qDebug() << "Current check state: " << isChecked;

                // 切换复选框状态
                //bool newCheckedState = isChecked ? Qt::Unchecked : Qt::Checked;
                //bool newCheckedState = (isChecked == Qt::Unchecked) ? Qt::Checked : Qt::Unchecked;
                Qt::CheckState newCheckedState = (isChecked == Qt::Unchecked) ? Qt::Checked : Qt::Unchecked;
                qDebug() << "model type: " << model->metaObject()->className();
                // 将模型强制转换为 QStandardItemModel
                //QStandardItemModel *standardModel = dynamic_cast<QStandardItemModel *>(model);
                QgsLayerTreeProxyModel *proxyModel = qobject_cast<QgsLayerTreeProxyModel *>(model);
                if (proxyModel) {
                    QAbstractItemModel *sourceModel = proxyModel->sourceModel();
                    // 通过 mapToSource 获取底层模型的索引
                    QModelIndex sourceIndex = proxyModel->mapToSource(index);  // 转换为源模型的索引
                    if (sourceIndex.isValid()) {
                        qDebug() << "Source index is valid, proceeding with data retrieval";

                        // 打印返回的 data 内容来检查类型
                        QVariant data = sourceModel->data(sourceIndex);
                        qDebug() << "Data at sourceIndex: " << data;

                        //QgsLayerTreeNode *node = dynamic_cast<QgsLayerTreeNode *>(sourceModel->data(sourceIndex).value<QObject*>());
                        // 如果返回的是图层名称（例如 "city333"），通过名称查找节点
                        //QString layerName = data.toString();
                        QgsLayerTreeNode *node = getLayerNodeByName(sourceIndex,model);  // 使用名称查找节点

                        if (node) {
                            // 更新节点的可见性
                            bool isVisible = (newCheckedState == Qt::Checked);
                            node->setItemVisibilityChecked(isVisible);  // 假设 setVisibility 控制可见性
                            return true;  // 事件已处理
                        } else {
                            qDebug() << "Failed to get QgsLayerTreeNode from index!";
                        }
                    } else {
                        qDebug() << "Model is not QgsLayerTreeProxyModel!";
                    }
                }

            }
            return QStyledItemDelegate::editorEvent(event, model, option, index);
        }
    }


    QgsLayerTreeNode* getLayerNodeByName(const QModelIndex &index,QAbstractItemModel *model)
    {
        // 获取底层模型
        QgsLayerTreeProxyModel *proxyModel = qobject_cast<QgsLayerTreeProxyModel *>(model);
        if (proxyModel) {
            QAbstractItemModel *sourceModel = proxyModel->sourceModel();

            QVariant data = sourceModel->data(index);
            QgsLayerTreeNode *node = dynamic_cast<QgsLayerTreeNode *>(data.value<QObject*>());

            if (node) {
                return node;
            }
        }
        return nullptr;  // 没有找到
    }
};
